import axios from 'axios';
import Cookies from 'js-cookie';
import { allStore } from '@/store/allStore';
import pinia from '@/store';
import router from '@/router';
import { ElMessage } from 'element-plus';
const store = allStore(pinia);

//1. 创建axios对象
const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 50000,
});

//2. 请求拦截器
request.interceptors.request.use(
  (config) => {
    // const token = Cookies.get('common-userInfo-key') as string;
    // if (token) {
    //   if (config && config.headers) {
    //     config.headers = config.headers || {};
    //     config.headers.Authorization = `Token ${token}` as string;
    //   }
    // }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

//3. 响应拦截器
request.interceptors.response.use(
  (response) => {
    //判断code码
    return response.data;
  },
  (error) => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          if (error.response.data.msg) {
            ElMessage.error(error.response.data.msg);
          } else {
            ElMessage.error('请求错误')
          }
          break
        case 401:
          ElMessage.error('未授权，请登录')
          Cookies.remove('common-userInfo-key');
          store.$state.userInfo = {};
          router.push('/login');
          break

        case 403:
          ElMessage.error('拒绝访问')
          break

        case 404:
          ElMessage.error('请求地址出错')
          break

        case 408:
          ElMessage.error('请求超时')
          break

        case 500:
          ElMessage.error('服务器内部错误')
          break

        case 501:
          ElMessage.error('服务未实现')
          break

        case 502:
          ElMessage.error('网关错误')
          break

        case 503:
          ElMessage.error('服务不可用')
          break

        case 504:
          ElMessage.error('网关超时')
          break

        case 505:
          ElMessage.error('HTTP版本不受支持')
          break
        default:
          ElMessage.error(error.message)
          break
      }
    }
    return Promise.reject(error);
  }
);

export default request;